<!--按需求创建送货计划-->
<template>
	<div class="m-view-selectDemandPlan m-window" v-loading="loading">
		<el-row :gutter="5">
			<el-col :span="2" class="m-floatRight">
				<el-button type="primary" @click="confirmCreate">确定</el-button>
			</el-col>
			<el-col :span="2" class="m-floatRight">
				<el-button @click="goBack">返回</el-button>
			</el-col>
		</el-row>
		<el-row :gutter="10">
			<el-form label-width="70px" :inline-message="true" label-position="left">
				<el-col :span="7">
					<el-form-item label="公司" class="rightItem">
						<el-select
							value-key="id"
							v-model="searchForm.companyCode"
							placeholder="请选择公司"
							clearable
							ref="content"
							filterable
						>
							<el-option
								v-for="item in comOptions"
								:key="item.id"
								:label="item.companyName"
								:value="item.companyCode"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="需求日期" class="rightItem">
						<el-date-picker
							v-model="searchForm.startSdate"
							type="date"
							placeholder="需求开始日期"
							value-format="yyyy-MM-dd"
						></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-date-picker
						v-model="searchForm.startEdate"
						type="date"
						placeholder="需求结束日期"
						value-format="yyyy-MM-dd"
					></el-date-picker>
				</el-col>
				<el-col :span="5">
					<el-form-item label="物料" class="rightItem">
						<el-input v-model="searchForm.materiel" placeholder="物料编码或描述"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="2" class="m-floatRight">
					<el-button type="primary" @click="searchDemandMxs">查询</el-button>
				</el-col>
			</el-form>
		</el-row>
		<!-- 内容主体 -->
		<div class="m-container">
			<div class="leftTabs">
				<el-tabs type="card" class="demandPlan-tabs">
					<el-tab-pane label="需求清单">
						<ag-grid-vue
							class="ag-theme-balham m-agTable"
							:gridOptions="gridOptions.requird"
							:columnDefs="columnDefs.requird"
							:rowData="rowData.requird"
							rowSelection="single"
						></ag-grid-vue>
					</el-tab-pane>
				</el-tabs>
			</div>
			<div class="rightTabs">
				<el-tabs type="card" class="demandPlan-tabs" v-model="tabName">
					<el-tab-pane label="未完成订单" name="1">
						<ag-grid-vue
							class="ag-theme-balham m-agTable grid-bottom"
							:gridOptions="gridOptions.noComplete"
							:columnDefs="columnDefs.noComplete"
							:rowData="rowData.noComplete"
							v-loading="orderLoading"
						></ag-grid-vue>
						<el-button type="primary" class="bottomBtn" @click="addToSelected">添加到已选</el-button>
					</el-tab-pane>
					<el-tab-pane label="已选订单" name="2">
						<ag-grid-vue
							class="ag-theme-balham m-agTable"
							:gridOptions="gridOptions.selected"
							:columnDefs="columnDefs.selected"
							:rowData="rowData.selected"
							v-loading="loading"
						></ag-grid-vue>
						<!-- <el-button type="primary" class="bottomBtn">取消已选</el-button> -->
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>
	</div>
</template>

<script>
import authInfo from "@/public/authInfo";
import gridOptions from "lesso-common/public/gridOptions";
import rendererFramework from './rendererFramework'
import Msg from "@/public/message"
/**
 * @group demandPlanList
 * 需求计划
*/
export default {
	name: 'selectDemandPlan',
	data () {
		return {
			// 查询参数
			searchForm: {
				companyCode: '',
				startSdate: new Date().Format("yyyy-MM-dd"),//默认开始日期为当前日期
				startEdate: new Date(new Date().getTime() + 3600 * 1000 * 24 * 7).Format("yyyy-MM-dd"),//默认结束日期为7天后日期
				materiel: ''
			},
			comOptions: [],
			// 表格配置
			gridOptions: {
				requird: {},
				noComplete: {},
				selected: {}
			},
			// 表格列配置
			columnDefs: {
				requird: [],
				noComplete: [],
				selected: []
			},
			// 表格数据
			rowData: {
				requird: [],
				noComplete: [],
				selected: []
			},
			loading: false,
			tabName: '1',
			orderLoading: false,
			// 已选择订单列表
			selectedRows: [],
			// 本次分配的物料需求
			selectDemands: {},
			totalPlanAmount: 0
		};
	},
	props: {
	},
	components: {},
	beforeMount () {
		this.gridOptions = {
			requird: {
				...gridOptions(),
				headerHeight: 70,
				rowHeight: 70,
				onRowSelected: this.selectedDemandPlan
			},
			noComplete: {
				...gridOptions(),
				headerHeight: 70,
				rowHeight: 70,
				pinnedBottomRowData: this.createBottomRow(1, "Bottom"),
				components: {
					customPinnedRowRenderer: CustomPinnedRowRenderer,
					customPinnedRowRenderer2: CustomPinnedRowRenderer2
				},
				context: {
					componentParent: this
				},
				getRowStyle: function (params) {
					if (params.node.rowPinned) {
						return { 'color': 'red', 'font-weight': "bold" }
					}
				},
			},
			selected: {
				...gridOptions(),
				headerHeight: 70,
				rowHeight: 70,
			}
		};
		this.columnDefs = {
			requird: [
				{
					headerName: "",
					field: "",
					width: 50,
					checkboxSelection: true,
					headerCheckboxSelection: true,
					cellStyle: { 'line-height': '70px' }
				},
				{
					headerName: "物料编号",
					field: "matName",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 140,
					width: 140,
				},
				{
					headerName: "需求日期",
					field: "startSdate",
					width: 100,
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					// minWidth: 200,
				},
				{
					headerName: "需求量",
					field: "requestAmount",
					width: 100,
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					// minWidth: 200,
				},
			],
			noComplete: [
				{
					headerName: "",
					field: "",
					width: 50,
					checkboxSelection: true,
					headerCheckboxSelection: true,
					cellStyle: { 'line-height': '70px' }
				},
				{
					headerName: "采购订单",
					field: "purOrdNo",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 140,
					width: 140,
				},
				{
					headerName: "供应商",
					field: "supplierName",
					// headerComponentFramework: rendererFramework.requireHeaderCell,
					// cellRendererFramework: rendererFramework.columnCell,
					tooltipField: "supplierName",
					minWidth: 160,
					cellStyle: { 'text-align': 'center', 'line-height': '70px' }
				},
				{
					headerName: "订单量",
					field: "orderAmount",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 120,
					width: 100,
				},
				{
					headerName: "确认量",
					field: "confirmAmount",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 100,
					width: 100,
				},
				{
					headerName: "可计划量",
					field: "planableAmount",
					// headerComponentFramework: rendererFramework.requireHeaderCell,
					// cellRendererFramework: rendererFramework.columnCell,
					minWidth: 100,
					width: 100,
					pinnedRowCellRenderer: 'customPinnedRowRenderer',
					cellStyle: { 'text-align': 'center', 'line-height': '70px' }
				},
				{
					headerName: "已计划量",
					field: "planedAmount",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.numberEditer,
					pinnedRowCellRenderer: 'customPinnedRowRenderer2',
					minWidth: 100,
					width: 100,
				},
			],
			selected: [
				{
					headerName: "采购订单",
					field: "purOrdNo",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 120,
					width: 120,
				},
				{
					headerName: "供应商",
					field: "supplierName",
					// cellRendererFramework: rendererFramework.columnCell,
					minWidth: 160,
					tooltipField: "supplierName",
					cellStyle: { 'text-align': 'center', 'line-height': '70px' }
				},
				{
					headerName: "物料编号",
					field: "matName",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 120,
					width: 120,
				},
				{
					headerName: "需求日期",
					field: "startSdate",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 90,
					width: 100,
				},
				{
					headerName: "订单量",
					field: "orderAmount",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 100,
					width: 100,
				},
				{
					headerName: "确认量",
					field: "confirmAmount",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 100,
					width: 100,
				},
				{
					headerName: "待交量",
					field: "deliveryNum",
					// cellRendererFramework: rendererFramework.columnCell,
					minWidth: 100,
					width: 100,
					cellStyle: { 'text-align': 'center', 'line-height': '70px' }
				},
				{
					headerName: "已计划量",
					field: "planedAmount",
					headerComponentFramework: rendererFramework.requireHeaderCell,
					cellRendererFramework: rendererFramework.requireColumnCell,
					minWidth: 120,
					width: 100,
				},
			]
		}
		this.getCompanyOption()
	},
	methods: {
        /**
		 * @vuese
		 * 返回创建送货计划页面
		*/
		goBack () {
			// 注册返回主页面事件
			this.$emit('goBack')
		},
        /**
		 * @vuese
		 * 选中需求清单明细获取未完成订单
		*/
		selectedDemandPlan (params) {
			if (params.node.selected) {
				this.orderLoading = true
				this.selectDemands = params.data
				this.tabName = '1'
				this.$http.getIncompleteOrder({ matCode: params.data.matCode }).then(({ data }) => {
					this.orderLoading = false
					if (data.code == 1) {
						if (Array.isArray(data.rows) && data.rows.length > 0) {
							this.rowData.noComplete = data.rows
							let totalAmount = 0
							this.rowData.noComplete.forEach(row => {
								totalAmount = 0
								this.$set(row, 'planAmount', 0)
								// 已选择订单类列表有相同订单行累计已计划数量
								if (this.rowData.selected.length > 0) {
									for (let k = 0; k < this.rowData.selected.length; k++) {
										if (this.rowData.selected[k].purOrdNo == row.purOrdNo
											&& this.rowData.selected[k].purOrdMxNo == row.purOrdMxNo) {
											if (!row.planedAmount) {
												totalAmount = Number(totalAmount) + Number(this.rowData.selected[k].planAmount);
											} else {
												totalAmount = Number(totalAmount) + Number(this.rowData.selected[k].planAmount) + Number(row.planedAmount);
											}
										}
									}
									row.planedAmount = totalAmount
								}
							})
						} else {
							this.rowData.noComplete = []
						}
					} else {
						this.rowData.noComplete = []
						Msg.showErrorMsg(data.info)
					}
					this.setPinnedData()
				}).catch(err => {
					this.orderLoading = false
					this.rowData.noComplete = []
					this.setPinnedData()
					Msg.showErrorMsg(err.data.message)
				})
			}
		},
        /**
		 * @vuese
		 * 查询未完成需求计划明细
        */
		searchDemandMxs () {
			let params = {
				...this.searchForm,
				startSdate: this.searchForm.startSdate ? `${this.searchForm.startSdate} 00:00:00` : '',
				startEdate: this.searchForm.startSdate ? `${this.searchForm.startEdate} 00:00:00` : ''
			}
			this.loading = true
			this.rowData.requird = []
			this.rowData.noComplete = []
			this.rowData.selected = []
			this.setPinnedData()
			this.$http.getDemandPlanMxs(params).then(({ data }) => {
				this.loading = false
				if (data.code == 1) {
					this.rowData.requird = data.rows
					this.rowData.requird.forEach(row => {
						// row.assigned = false
						this.$set(row, 'assigned', false)
					})
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
        /**
		 * @vuese
		 * 添加到已选列表
		*/
		addToSelected () {
			let rows = this.gridOptions.noComplete.api.getSelectedRows()
			let _this = this
			if (rows.length == 0) {
				Msg.showPopMsg('请选择你要分配的订单!')
				return
			}
			if (this.totalPlanAmount > this.selectDemands.planableQuantity) {
				Msg.showPopMsg('已分配计划量不可大于当前需求明细可计划量,请重新分配')
				return
			}
			// 编辑计划数量验证
			for (let i = 0; i < rows.length; i++) {
				if (rows[i].planAmount == 0) {
					Msg.showPopMsg(`订单号${rows[i].purOrdNo}行号${rows[i].purOrdMxNo}的计划量不能为0`)
					return
				} else if (rows[i].planAmount > rows[i].planableAmount) {
					Msg.showPopMsg(`订单号${rows[i].purOrdNo}行号${rows[i].purOrdMxNo}的计划量不能大于可计划量,请重新分配!`)
					return
				} else if (rows[i].planedAmount > rows[i].planableAmount) {
					Msg.showPopMsg(`订单号${rows[i].purOrdNo}行号${rows[i].purOrdMxNo}的已分配计划量大于可计划量,请重新分配!`)
					return
				}
			}
			rows.forEach(row => {
				this.rowData.selected.forEach(sel => {
					if (sel.purOrdNo == row.purOrdNo && sel.purOrdMxNo == row.purOrdMxNo) {
						sel.planedAmount = row.planedAmount
					}
				})
				// 组装已选择订单数据
				this.rowData.selected.push({
					...row,
					...this.selectDemands
				})
			})
			this.tabName = '2'
			this.gridOptions.noComplete.api.forEachNode(function (node) {
				if (node.selected) {
					node.selectable = false
				}
			})
			// 已分配的不可选
			this.gridOptions.requird.api.forEachNode(function (node) {
				if (node.data.id == _this.selectDemands.id) {
					node.data.assigned = true
					node.selectable = false
				}
			})
		},
		/**
		 * @vuese
		 * 确认创建送货计划单
		*/
		confirmCreate () {
			this.$emit("confirmCreate", this.rowData.selected)
		},
        /**
		 * @vuese
		 * 创建底部合计栏
		*/
		createBottomRow (count, prefix) {
			var result = [{
				deliveryNum: '合计',
				planedAmount: this.totalPlanAmount
			}
			]
			return result
		},
        /**
		 * @vuese
		 * 设置底部合计总数
		*/
		setPinnedData () {
			this.totalPlanAmount = 0
			this.rowData.noComplete.forEach(row => {
				this.totalPlanAmount += Number(row.planAmount)
			})
			this.$nextTick(_ => {
				this.gridOptions.noComplete.api.setPinnedBottomRowData(this.createBottomRow(1, "Bottom"))
			})
		},
        /**
		 * @vuese
		 * 根据账户类型获取所属公司下拉列表
		*/
		getCompanyOption () {
			this.loading = true
			authInfo.getAuthInfo().then(data => {
				this.comOptions = data
				this.searchForm.companyCode = this.comOptions[0].companyCode
				this.searchDemandMxs()
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg('服务器或网络异常!')
			});
		},
	},
};
function CustomPinnedRowRenderer () { }

CustomPinnedRowRenderer.prototype.init = function (params) {
	this.eGui = document.createElement('div');
	this.eGui.style.lineHeight = '70px'
	this.eGui.style.textAlign = 'center'
	this.eGui.innerHTML = '合计'
};

CustomPinnedRowRenderer.prototype.getGui = function () {
	return this.eGui
}
function CustomPinnedRowRenderer2 () { }
CustomPinnedRowRenderer2.prototype.init = function (params) {
	delete params.data.confirmAmount;
	this.eGui = document.createElement('div');
	this.eGui.setAttribute('id', 'totalCell');
	this.eGui.style.textAlign = 'center'
	this.eGui.style.lineHeight = '70px'
	let child1 = document.createElement('p')
	child1.innerHTML = params.value
	this.eGui.appendChild(child1)
};

CustomPinnedRowRenderer2.prototype.getGui = function () {
	return this.eGui
}
</script>

<style lang="less" scoped>
.m-view-selectDemandPlan {
	.m-container {
		display: flex;
		height: calc(100% - 105px);
		.leftTabs {
			flex-basis: 400px;
			position: relative;
		}
		.rightTabs {
			flex: 1;
			margin-left: 25px;
			position: relative;
		}
		.demandPlan-tabs {
			/deep/ .el-tabs__content {
				top: 40px;
				left: 0;
				right: 0;
				.m-agTable {
					position: absolute;
					top: 0;
					bottom: 5px;
					left: 0;
					right: 0;
				}
				.grid-bottom {
					bottom: 50px !important;
				}
				.bottomBtn {
					position: absolute;
					bottom: 5px;
					left: 0;
					right: 0;
				}
			}
			/deep/ .el-tabs__item.is-top.is-active {
				background: #409eff;
				color: #fff;
			}
		}
	}
}
</style>
